package milu.servlets;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.jdo.PersistenceManager;
import com.google.appengine.api.datastore.Blob;
import milu.*;
import milu.models.*;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

import com.google.appengine.api.datastore.*;

public class Serve extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        String[] segments = req.getRequestURI().split("/");
        String imageId = null;
        if(segments.length >= 3)
            imageId = segments[2];

        String[] fileSplit = imageId.split("\\."); // it ends with .png
        imageId = fileSplit[0];

        // find desired image
        PersistenceManager pm = Datastore.getPersistenceManager();
        Key k = KeyFactory.createKey(MyImage.class.getSimpleName(), Long.parseLong(imageId));
        MyImage myImage = pm.getObjectById(MyImage.class, k);

        Blob image = myImage.getImageBin();
        byte[] imageBytes = image.getBytes();


        // serve the first image
        res.setHeader("Cache-Control", "max-age=315360000");
        res.setContentType("image/png");
        res.getOutputStream().write(imageBytes);
    }
}
